package com.lagou.edu.filter;

import cn.hutool.core.util.StrUtil;
import com.lagou.edu.feignservice.UserService;
import com.netflix.discovery.converters.Auto;
import jdk.nashorn.internal.ir.CallNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: springcloud-web-one
 * @description: 鉴权管理
 * @author: zhoushiduo
 * @create: 2021-03-26 11:10
 */

@Component
@Slf4j
public class AuthManageFilter implements GlobalFilter, Ordered {

    private static List<String> whiteUri =  new ArrayList<>();

    static {
        whiteUri.add("/user/");
        whiteUri.add("/code/");
    }

    @Autowired
    private UserService userService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        boolean isWhiteUri = false;
        String path = exchange.getRequest().getPath().value();
        for (String uri : whiteUri) {
            int i = path.indexOf(uri);
            if (i >= 0) {
                isWhiteUri = true;
            }
        }

        //白名单不进行鉴权
        if (isWhiteUri) {
            return chain.filter(exchange);
        }

        //进行鉴权
        Map<String, Object> attributes = exchange.getAttributes();
        boolean isLogin = false;
        if (attributes.containsKey("token")) {
            String email = userService.info(attributes.get("token").toString());
            if (StrUtil.isNotBlank(email)) {
                isLogin = true;
                log.info("登录用户：" + email);
            }
        }

        if (!isLogin) {
            ServerHttpResponse response = exchange.getResponse();
            String hostName = exchange.getRequest().getRemoteAddress().getHostName();
            // 决绝访问，返回
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            log.debug("=====>IP:" + hostName + " 没有访问权限，将被拒绝访问！");
            String data = "Request be denied! 没有访问权限，将被拒绝访问！";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
